import trackService from '@/services/track-service';
import {
  MailOutlined,
  ReloadOutlined,
  SearchOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { useDebounceFn, useRequest } from 'ahooks';
import {
  Button,
  Card,
  DatePicker,
  Divider,
  Input,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useCallback, useEffect, useMemo, useState } from 'react';

const { Text, Title } = Typography;
const { RangePicker } = DatePicker;

interface QuestionItem {
  id: string;
  anonymous_user_id: string;
  login_user_email: string;
  conversation_id: string;
  question: string;
  answer: string;
  timestamp: string;
}

interface PaginationParams {
  page: number;
  page_size: number;
  anonymous_user_id?: string;
  login_user_email?: string;
  start_date?: string;
  end_date?: string;
}

const UserTrack = () => {
  const [params, setParams] = useState<PaginationParams>({
    page: 1,
    page_size: 10,
    anonymous_user_id: '',
    login_user_email: '',
    start_date: '',
    end_date: '',
  });
  const { data, loading, run } = useRequest(
    async (params: PaginationParams) => {
      try {
        const res = await trackService.get_question({
          page: params.page,
          page_size: params.page_size,
          anonymous_user_id: params.anonymous_user_id,
          login_user_email: params.login_user_email,
          start_date: params.start_date,
          end_date: params.end_date,
        });
        const response = res.data;

        if (response.code !== 0) {
          message.error(response.message || '获取数据失败');
          return {
            list: [],
            total: 0,
            page: 1,
            page_size: 10,
          };
        }

        return response.data;
      } catch (error) {
        console.error('请求错误:', error);
        message.error('请求异常');
        return {
          list: [],
          total: 0,
          page: 1,
          page_size: 10,
        };
      }
    },
    {
      manual: true,
      defaultParams: [params],
    },
  );

  const { run: debounceRun } = useDebounceFn(
    (params: PaginationParams) => {
      run(params); // 实际发起请求的函数
    },
    { wait: 500 }, // 防抖延迟时间（单位：毫秒）
  );

  useEffect(() => {
    debounceRun(params); // 防抖后的调用
  }, [params, debounceRun]);

  const tableData = useMemo(
    () => ({
      list: data?.list || [],
      total: data?.total || 0,
      page: data?.page || 1,
      page_size: data?.page_size || 10,
    }),
    [data],
  );

  const handleSearch = useCallback(() => {
    run(params);
  }, [run]);

  const handleReset = useCallback(() => {
    setParams({
      page: 1,
      page_size: 10,
      anonymous_user_id: '',
      login_user_email: '',
      start_date: '',
      end_date: '',
    });
  }, []);

  const handleDateChange = useCallback(
    (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
      setParams((prev) => ({
        ...prev,
        start_date: dates?.[0]?.format('YYYY-MM-DD') || '',
        end_date: dates?.[1]?.format('YYYY-MM-DD') || '',
        page: 1,
      }));
    },
    [],
  );

  const handlePaginationChange = useCallback(
    (page: number, pageSize: number) => {
      setParams((prev) => ({
        ...prev,
        page,
        page_size: pageSize,
      }));
    },
    [],
  );

  const columns: ColumnsType<QuestionItem> = useMemo(
    () => [
      {
        title: '用户信息',
        key: 'user_info',
        width: 250,
        fixed: 'left',
        render: (_, record) => (
          <Space direction="vertical" size={4}>
            {record.anonymous_user_id && (
              <div>
                <Tag icon={<UserOutlined />} color="blue">
                  匿名ID
                </Tag>
                <Text copyable>{record.anonymous_user_id}</Text>
              </div>
            )}
            {record.login_user_email && (
              <div>
                <Tag icon={<MailOutlined />} color="green">
                  登录邮箱
                </Tag>
                <Text copyable>{record.login_user_email}</Text>
              </div>
            )}
            {!record.anonymous_user_id && !record.login_user_email && (
              <Text type="secondary">未识别用户</Text>
            )}
          </Space>
        ),
      },
      {
        title: '对话id',
        dataIndex: 'conversation_id',
        key: 'conversation_id',
        width: 300,
        render: (text) => (
          <Text
            ellipsis={{ tooltip: text }}
            style={{
              maxWidth: '100%',
              display: 'inline-block',
              lineHeight: 1.5,
            }}
          >
            {text}
          </Text>
        ),
      },
      {
        title: '提问内容',
        dataIndex: 'question',
        key: 'question',
        width: 300,
        render: (text) => (
          <Text
            ellipsis={{ tooltip: text }}
            style={{
              maxWidth: '100%',
              display: 'inline-block',
              lineHeight: 1.5,
            }}
          >
            {text}
          </Text>
        ),
      },
      {
        title: '回答内容',
        dataIndex: 'answer',
        key: 'answer',
        width: 500,
        render: (text) => (
          <div
            style={{
              maxHeight: 150,
              overflow: 'auto',
              padding: '8px 12px',
              background: '#fafafa',
              borderRadius: 4,
              border: '1px solid #f0f0f0',
            }}
          >
            {text || <Text type="secondary">暂无回答</Text>}
          </div>
        ),
      },
      {
        title: '时间',
        dataIndex: 'timestamp',
        key: 'timestamp',
        width: 180,
        sorter: (a, b) => dayjs(a.timestamp).unix() - dayjs(b.timestamp).unix(),
        render: (text) => (
          <Tag color="geekblue">{dayjs(text).format('YYYY-MM-DD HH:mm')}</Tag>
        ),
      },
    ],
    [],
  );

  return (
    <div style={{ padding: 24 }}>
      <Card
        title={
          <Title level={4} style={{ margin: 0 }}>
            用户问答历史
          </Title>
        }
        bordered={false}
        headStyle={{ borderBottom: '1px solid #f0f0f0' }}
        bodyStyle={{ padding: '16px 0' }}
      >
        <div style={{ padding: '0 24px 16px' }}>
          <Space wrap>
            <Input
              placeholder="匿名用户ID"
              value={params.anonymous_user_id}
              onChange={(e) =>
                setParams((prev) => ({
                  ...prev,
                  anonymous_user_id: e.target.value,
                }))
              }
              allowClear
              prefix={<UserOutlined />}
              style={{ width: 240 }}
            />
            <Input
              placeholder="登录用户邮箱"
              value={params.login_user_email}
              onChange={(e) =>
                setParams((prev) => ({
                  ...prev,
                  login_user_email: e.target.value,
                }))
              }
              allowClear
              prefix={<MailOutlined />}
              style={{ width: 240 }}
            />
            <RangePicker
              onChange={handleDateChange}
              style={{ width: 280 }}
              disabledDate={(current) =>
                current && current > dayjs().endOf('day')
              }
            />
            <Button
              type="primary"
              onClick={handleSearch}
              icon={<SearchOutlined />}
              loading={loading}
            >
              搜索
            </Button>
            <Button onClick={handleReset} icon={<ReloadOutlined />}>
              重置
            </Button>
          </Space>
        </div>

        <Divider style={{ margin: '16px 0' }} />

        <div style={{ padding: '0 24px' }}>
          <Table
            columns={columns}
            dataSource={tableData.list}
            loading={loading}
            rowKey="id"
            scroll={{
              x: '100%',
            }}
            pagination={{
              current: params.page,
              pageSize: params.page_size,
              total: tableData.total,
              onChange: handlePaginationChange,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            bordered
            size="middle"
          />
        </div>
      </Card>
    </div>
  );
};

export default UserTrack;
